// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <nebula/json/object_writer.h>
#include <nebula/json/rapidjson_defs.h>  // IWYU pragma: keep

#include <merak/json.h>


namespace nebula::json::internal {

    class ObjectWriter::Impl {
    public:
        Impl() : root_(merak::json::kObjectType) {}

        void set_string(std::string_view key, std::string_view value) {
            merak::json::Document::AllocatorType &allocator = document_.get_allocator();

            merak::json::Value str_key(key.data(), allocator);
            merak::json::Value str_value(value.data(), allocator);

            root_.add_member(str_key, str_value, allocator);
        }

        void set_bool(std::string_view key, bool value) {
            merak::json::Document::AllocatorType &allocator = document_.get_allocator();

            merak::json::Value str_key(key.data(), allocator);

            root_.add_member(str_key, value, allocator);
        }

        std::string serialize() {
            merak::json::StringBuffer buffer;
            merak::json::Writer<merak::json::StringBuffer> writer(buffer);
            root_.accept(writer);

            return buffer.get_string();
        }

    private:
        merak::json::Document document_;
        merak::json::Value root_;
    };

    ObjectWriter::ObjectWriter() : impl_(new ObjectWriter::Impl()) {}

    ObjectWriter::~ObjectWriter() = default;

    void ObjectWriter::set_string(std::string_view key, std::string_view value) {
        impl_->set_string(key, value);
    }

    void ObjectWriter::set_bool(std::string_view key, bool value) {
        impl_->set_bool(key, value);
    }

    std::string ObjectWriter::serialize() { return impl_->serialize(); }

}  // namespace nebula::json::internal
